#include "servernetworkprocessing.h"
#include <QTcpSocket>
#include <QtWidgets>
#include "clientlist.h"
ServerNetworkProcessing::ServerNetworkProcessing()
{
    m_tcpServer = new QTcpSocket(this);
    //connect(m_tcpServer,SIGNAL(connected()),this,SLOT(startTransfer()));
    //connect(m_tcpServer,SIGNAL(bytesWritten(qint64)),this,SLOT(updateClientProgress(qint64)));
    connect(m_tcpServer,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));
    connect(m_tcpServer,SIGNAL(readyRead()),this,SLOT(updateServerProgress()));
    //connect(m_tcpServer,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));
}
bool ServerNetworkProcessing::Connection(QString ipAddr, int port)
{
    m_tcpServer->connectToHost(ipAddr, port);
    qDebug()<<"开始连接客户机";
    return getTcpServerStatic();
}
void ServerNetworkProcessing::send(QJsonObject sendJson){
    // start to sending
    qDebug()<<"开始发送数据";
    qDebug()<<sendJson;
    QJsonDocument jsonDocument;
    jsonDocument.setObject(sendJson);
    QByteArray dataArray = jsonDocument.toJson();
    int sendLength = m_tcpServer->write(dataArray,dataArray.length());
    qDebug()<<"send data size:"<<sendLength;
}

void ServerNetworkProcessing::displayError(QAbstractSocket::SocketError){
    qDebug()<< "displayError: " << m_tcpServer->errorString();
    m_tcpServer->close();
    SendSignal(false);
}
void ServerNetworkProcessing::SendSignal(bool flag)
{
    emit TcpSockerStatic(flag);
}
bool ServerNetworkProcessing::getTcpServerStatic()
{
    if (m_tcpServer->waitForConnected(1000))  // 连接成功则进入if{}
    {
        qDebug()<<"连接成功";
        return true;
    }
    qDebug()<<"连接失败";
    return false;
}
